package user_private_key

import (
	"chain_bridge_service/internal/code"
	"chain_bridge_service/internal/pkg/core"
	"chain_bridge_service/internal/pkg/validation"
	"chain_bridge_service/internal/repository/mongodb/user"
	"chain_bridge_service/internal/services/user_private_key"
	"net/http"
)

type createRequest struct {
	Id              string `bson:"_id,omitempty" json:"id"`
	UserId          string `bson:"userId" json:"userId"`
	MainCoinType    int64  `bson:"mainCoinType" json:"mainCoinType"`                 // udun的id
	FeeAddress      string `bson:"feeAddress,omitempty" json:"feeAddress"`           // 手续费地址（私钥）
	CollectAddress  string `bson:"collectAddress,omitempty" json:"collectAddress"`   // 归集地址
	WithdrawAddress string `bson:"withdrawAddress,omitempty" json:"withdrawAddress"` // 提币地址（私钥）
	ChainName       string `bson:"chainName" json:"chainName"`
}

type createResponse struct {
	Code int         `json:"code"`
	Data interface{} `json:"data"`
	Msg  string      `json:"msg"`
}

func (h *handler) Create() core.HandlerFunc {
	return func(ctx core.Context) {
		req := new(createRequest)
		res := new(createResponse)
		if err := ctx.ShouldBindJSON(req); err != nil {
			ctx.AbortWithError(core.Error(
				http.StatusOK,
				code.ParamBindError,
				validation.Error(err)).WithError(err),
			)
			return
		}

		userInfo := ctx.GetInfo("userInfo").(*user.User)
		createData := new(user_private_key.UserPrivateKeyData)
		createData.UserId = userInfo.Id
		createData.MainCoinType = req.MainCoinType
		createData.CollectAddress = req.CollectAddress
		createData.FeeAddress = req.FeeAddress
		//createData.WithdrawAddress = req.WithdrawAddress
		createData.ChainName = req.ChainName
		err := h.keyService.Create(ctx, createData)
		if err != nil {
			ctx.AbortWithError(core.Error(
				http.StatusOK,
				code.UserPrivateKeyCreateError,
				code.Text(code.UserPrivateKeyCreateError)).WithError(err),
			)
			return
		}

		res.Code = code.StatusOK
		res.Data = nil
		res.Msg = code.Text(code.StatusOK)
		ctx.Payload(res)
	}
}
